package com.yjdb.sanyuantang.generator.source;

import com.yjdb.sanyuantang.config.GlobalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.Map;

public class YamlReader {
    private static final Logger logger = LoggerFactory.getLogger(GlobalException.class);
    public String getType(){
        Yaml yaml = new Yaml();
        String type= null;
        try (InputStream in = YamlReader.class.getResourceAsStream("/application.yaml")) {
            Map<String, Object> yamlData = yaml.load(in);
            Map<String, Object> spring = (Map<String, Object>) yamlData.get("spring");
            Map<String, Object> profiles = (Map<String, Object>) spring.get("profiles");
            type = (String) profiles.get("active");
        } catch (Exception e) {
            logger.debug("YamlReader:getType", e);
        }
        return type;
    }

    public DataBaseEntity getDatabase() {
        Yaml yaml = new Yaml();
        String type= getType();
        String path = "/application-"+type+".yaml";
        DataBaseEntity dataBaseEntity = new DataBaseEntity();
        try (InputStream in = YamlReader.class.getResourceAsStream(path)) {
            Map<String, Object> yamlData = yaml.load(in);
            Map<String, Object> spring = (Map<String, Object>) yamlData.get("spring");
            Map<String, Object> datasource = (Map<String, Object>) spring.get("datasource");
            dataBaseEntity.setUrl((String) datasource.get("url"));
            dataBaseEntity.setUsername((String) datasource.get("username"));
            dataBaseEntity.setPassword(datasource.get("password").toString());
        } catch (Exception e) {
            logger.debug("YamlReader:getDatabase", e);
        }
        return dataBaseEntity;
    }
}
